package Server6BySelf;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    static ServerSocket serverSocket;
    private Socket socket;
    static {
        try {
            System.out.println("申请端口");
            serverSocket=new ServerSocket(8088);
            System.out.println("申请端口成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while (true){
                System.out.println("服务端正在等待链接");
                socket=serverSocket.accept();
                System.out.println("客户端已经链接");

                Servers s=new Servers(socket);
                Thread t=new Thread(s);
                t.start();//可多个用户链接
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    class Servers implements Runnable{
        Socket socket;
        List<PrintWriter> pwlist=new ArrayList<>();

        public Servers(Socket socket){
            this.socket=socket;
        }

        @Override
        public void run() {
            try {
                InputStream is=socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(is,"utf-8");
                BufferedReader br=new BufferedReader(isr);

                OutputStream fos=socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
                BufferedWriter bw=new BufferedWriter(osw);
                PrintWriter pw=new PrintWriter(bw,true);//设置为true才会自动换行发送

                pwlist.add(pw);


                String host=socket.getInetAddress().getHostAddress();//.toString会有杠ip地址/127.0.0.1，
                if (host!=null){
                    sendMessage(host);
                }


                String line;
                while ((line= br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                    System.out.println("客户端已经断开");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public void sendMessage(String message){
            for (PrintWriter p:pwlist){
                p.println(message);
            }
        }
    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }
}
